#-*-perl-*-
use Test::More qw(no_plan);
use Module::Build;
use strict;
use warnings;
use lib '../lib';

use_ok 'AlienArena::ServerFactory';
my $svr;
ok $svr = AlienArena::ServerFactory->create_server_no_console;
isa_ok $svr, 'AlienArena::Server';
ok $svr = AlienArena::ServerFactory->create_server('127.0.0.1','27901','s3kr1t');
isa_ok $svr, 'AlienArena::Server';
is $svr->host, '127.0.0.1', 'host set';
is $svr->port, 27901, 'port set';
is $svr->pass, 's3kr1t', 'pass set';
my ($host,$port,$pass);
my $do_live_tests;
my $pfile_exists = open my $p, 'p';
if ($pfile_exists){
    my $l = <$p>;
    ($host,$port,$pass) = split /\t/,$l;
}
elsif (Module::Build->current) {
    my $build = Module::Build->current;
    ($host,$port,$pass) = ($build->notes('test_host'),
			   $build->notes('test_port'),
			   $build->notes('test_pass'));
}
else {
    ($host, $port, $pass) = @ENV{qw(AA_HOST AA_PORT AA_PASS)};
}

if ($host && $port && $pass) {
    $do_live_tests = 1;
}
else {
  diag 'For live server tests, set AA_HOST, AA_PORT, and AA_PASS';
}
my $live_tests = 11;
SKIP : {
    skip 'Live server info not available', $live_tests unless $do_live_tests;
    ok $svr = AlienArena::ServerFactory->create_server_and_init($host,$port,$pass), 'create and init';
    ok $svr->is_up, "server is up";
    ok $svr->update_cvars;
    cmp_ok scalar $svr->cvarlist, ">", 100, ">100 cvars - v7.53";
    ok $svr->dmflags, "dmflags there";
    isa_ok $svr->dmflags, 'AlienArena::Server::CVar::DMFlags';
    cmp_ok scalar $svr->maplist, ">=", 3, "some maps in the maplist";
    is $svr->current_map, $svr->get_cvar('mapname')->value, "current map up to date";
    $svr->update_players;
    # test Commands
    my $rand = int(rand()*1000);
    my $resp = $svr->Set('boog', $rand);
    SKIP : {
	skip 'server error', 1 unless $resp && $resp->ok;
	$svr->update_cvars;
	is $svr->get_cvar('boog')->value, $rand, 'cvar boog set by Set';
    }
    $resp = $svr->Z_Stats;
    SKIP : {
	skip 'server error', 1 unless $resp && $resp->ok;
	like $resp->parsed_response, qr/[0-9]+ bytes in [0-9]+ blocks/, 'z_stats retrived by Z_Stats';
    }
    like $svr->Var('version'), qr/^7.5/, 'Var(version)';
    1;
}


